package http_servicer

import (
	//	"encoding/json"
	"fmt"
	"ifms/db_servicer"
	"net/http"
	"strconv"
)

func registerHandler(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, "Register:", log.LstdFlags|log.Lshortfile)
	//注册时不考虑地址信息

	v_account := request.FormValue("account")
	v_password := request.FormValue("password")
	v_password2 := request.FormValue("password2")
	v_username := request.FormValue("username")
	v_country_id := request.FormValue("country_id")
	v_addr_id := request.FormValue("addr_id")
	v_street_info := request.FormValue("street_info")

	logger.Println("account:", v_account, ",pass:", v_password, ", pass2:", v_password2, ",username:", v_username)
	//           ",prov:",v_province, ",city:", v_city,",distric:",v_distric, ", street:", v_street)

	var msg string
	var country_id, addr_id int
	var err error
	if v_password2 != v_password {

		msg = `{"flag": -1, "message": "密码不符，请重新输入"}`

	} else {

		if country_id, err = strconv.Atoi(v_country_id); err != nil && v_country_id != "" {
			country_id = 0
		}
		if addr_id, err = strconv.Atoi(v_addr_id); err != nil && v_addr_id != "" {
			addr_id = 0
		}

		dbmsg := db_servicer.User_Register(v_account, v_password, v_username, int32(country_id), int32(addr_id), v_street_info)

		msg = dbmsg.Data

	}

	logger.Println("\n>>>Return to App Client:", msg)

	fmt.Fprint(response, msg)

}

func loginstatusHandler(response http.ResponseWriter, request *http.Request) {

	// logger = log.New(os.Stdout, ">>>>>>>Login Status:", log.LstdFlags|log.Lshortfile)

	session_id, user_id := getAccountName(request)

	var msg string

	//		if session_id == account && user_id > 0  {   // Need to be improved later
	if session_id != "" && user_id > 0 {

		msg = `{"flag": 0, "message": "身份验证成功"}`

	} else {
		msg = `{"flag": -1, "message": "身份验证失败"}`

	}

	logger.Println("\n>>>Return to App Client:", msg)

	fmt.Fprint(response, msg)

}

func chgpwdHandler(response http.ResponseWriter, request *http.Request) {

	// logger = log.New(os.Stdout, ">>>>>>>Change Password:", log.LstdFlags|log.Lshortfile)

	old_pass := request.FormValue("old_pass")
	new_pass := request.FormValue("new_pass")
	re_pass := request.FormValue("re_pass")

	session_id, user_id := getAccountName(request)

	logger.Println("old pass :", old_pass, ", new pass:", new_pass,
		",session_id:", session_id,
		",user_id : ", user_id)
	//	redirectTarget := "/"

	var msg string

	if session_id == "" || user_id <= 0 {
		msg = `{"flag": -1, "message": "身份验证失败，请先登录再修改密码"}`
	} else if old_pass == "" || new_pass == "" {
		msg = `{"flag":-2, "message":"原密码或新密码为空，请检查输入"}	`
	} else if new_pass != re_pass {
		msg = `{"flag":-3, "message":"两次输入的密码不匹配，请重新输入"}	`

	} else {
		// login

		dbmsg := db_servicer.Chang_password(user_id, session_id, old_pass, new_pass)
		msg = dbmsg.Data

	}

	logger.Println("\n>>>Return to App Client:", msg)
	fmt.Fprint(response, msg)
}

func loginHandler(response http.ResponseWriter, request *http.Request) {

	// logger = log.New(os.Stdout, ">>>>>>>Login:", log.LstdFlags|log.Lshortfile)

	var client_port int32
	account := request.FormValue("account")
	pass := request.FormValue("password")

	client_ip, client_port, err := GetIP(request)
	if err != nil {
		client_ip = "unknown"
		client_port = 0
	}

	session_id, user_id := getAccountName(request)

	logger.Println("account:", account, "session_id:", session_id,
		"Client IP Addr: ", client_ip, ":", client_port)
	// //	redirectTarget := "/"

	var msg string

	if account == "" || pass == "" { // session_id == "" &&

		// If no session_id, then account&pass must be presented
		msg = `{"flag":-1, "message":"用户名或密码为空，请检查输入"}	`
	} else if account != "" && pass != "" {
		// login

		dbmsg := db_servicer.User_Auth(session_id, account, pass, client_ip, client_port)

		logger.Printf("db_service.User_Auth returns: %v\n", dbmsg)

		if dbmsg.Flag == 0 {
			//login succesed

			setSession(account, dbmsg.User_id, response)

		}
		msg = dbmsg.Data

	} else if session_id != "" && account != "" {
		// retrun session, verify account only
		if session_id == account && user_id > 0 {

			msg = `{"flag": 0, "message": "身份验证成功"}`

		} else {
			msg = `{"flag": -1, "message": "身份验证失败"}`

		}
	}

	/*  ***********************     The following block is only for test purpose   ***********************   */
	if request.FormValue("test") == "test" {
		fmt.Fprint(response, indexPage)
		fmt.Fprint(response, logoutPage)

		/* **************************************************************************************************** */
	} else {
		logger.Println("\n>>>Return to App Client:", msg)
		fmt.Fprint(response, msg)

		//	http.Redirect(response, request, redirectTarget, 302)
	}
}

func logoutHandler(response http.ResponseWriter, request *http.Request) {
	session_id, user_id := getAccountName(request)

	clearSession(response)
	//	http.Redirect(response, request, "/", 302)
	msg := `{"flag": 0, "message": "退出登录"}`
	logger.Printf("user %v(%v) logout", session_id, user_id)
	fmt.Fprint(response, msg)
}

func setSession(accountName string, user_id int, response http.ResponseWriter) {
	value := map[string]string{
		"account": accountName,
		"user_id": fmt.Sprint(user_id),
	}
	if encoded, err := cookieHandler.Encode("BjKjDxJjGlXy", value); err == nil {
		cookie := &http.Cookie{
			Name:  "BjKjDxJjGlXy",
			Value: encoded,
			Path:  "/",
		}
		http.SetCookie(response, cookie)
	}
}

func getAccountName(request *http.Request) (accountName string, user_id int) {
	var v_accountName string
	var v_user_id int = 0
	if cookie, err := request.Cookie("BjKjDxJjGlXy"); err == nil {
		cookieValue := make(map[string]string)
		if err = cookieHandler.Decode("BjKjDxJjGlXy", cookie.Value, &cookieValue); err == nil {
			v_accountName = cookieValue["account"]
			v_user_id, err = strconv.Atoi(cookieValue["user_id"])
		}
	}
	//	accountName = v_accountName
	//	user_id     = v_user_id
	return v_accountName, v_user_id
}

func clearSession(response http.ResponseWriter) {
	cookie := &http.Cookie{
		Name:   "BjKjDxJjGlXy",
		Value:  "",
		Path:   "/",
		MaxAge: -1,
	}
	http.SetCookie(response, cookie)
}

func versionHandler(response http.ResponseWriter, request *http.Request) {
	// accountName, user_id := getAccountName(request)
	// fmt.Println(" in Interal Page Handle, Account name : ", accountName, "User_ID:", user_id )
	// if accountName != "" {
	//     fmt.Fprint(response, indexPage )
	//     fmt.Fprintf(response, internalPage, accountName)
	// } else {
	//     http.Redirect(response, request, "/", 302)
	// }

	fmt.Fprintf(response, "Version: %v", version)
}

func internalPageHandler(response http.ResponseWriter, request *http.Request) {
	accountName, user_id := getAccountName(request)
	fmt.Println(" in Interal Page Handle, Account name : ", accountName, "User_ID:", user_id)
	if accountName != "" {
		fmt.Fprint(response, indexPage)
		fmt.Fprintf(response, internalPage, accountName)
	} else {
		http.Redirect(response, request, "/", 302)
	}
}

func reloginPage(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, ">>>>>>> re-login Page:", log.LstdFlags|log.Lshortfile)

	msg := `{"flag":-1,"message":"未登录或进程过期，请重新登录！" }`

	// this function is only for HTTP SVR test purpose
	// In production, nobody shuld call this function for ti break the protocal with Androp App
	// ONLY return JSON to client in production, no re-direction like in this function

	//		fmt.Fprintf(response, loginPage,  string(responseStr))
	logger.Println("\n>>>Return to App Client:", msg)
	fmt.Fprint(response, msg)

}
